package com.itheima.askme.controller;


import com.itheima.askme.entity.User;
import com.itheima.askme.service.IUserService;
import com.itheima.askme.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.UnsatisfiedServletRequestParameterException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dafei
 * @since 2022-06-14
 */
@RestController
@RequestMapping("users")
public class UserController {

    @Autowired
    private IUserService iUserService;
    @GetMapping("/detail")
    public User detail(Long id){
       return  iUserService.getById(id);
    }

   @PostMapping("/regist")
    public JsonResult regist(String username, String password, String code, HttpSession session){

       String regist_code = session.getAttribute("regist_code").toString();
       if (code==null || !code.equalsIgnoreCase(regist_code)){
           return  JsonResult.error("验证码错误");
       }
       try {
           iUserService.regist(username,password);
       }catch (Exception e){
           return JsonResult.error(e.getMessage());
       }
       return JsonResult.success();
   }


    @PostMapping("/login")
    public JsonResult login(String username, String password, String code, HttpSession session){

        String login_code = session.getAttribute("login_code").toString();
        if (code==null || !code.equalsIgnoreCase(login_code)){
            return  JsonResult.error("验证码错误");
        }
        try {
            User  user=  iUserService.login(username,password);
            session.setAttribute("user_in_session",user);
            return JsonResult.success(user);
        }catch (Exception e){
            return JsonResult.error(e.getMessage());
        }
    }


    @GetMapping("/rank")
    public JsonResult rank(){

        List<User> list=iUserService.rank();

      return  JsonResult.success(list);
    }

}
